package hig.no.group;


import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class GetGPSLocation extends Activity implements OnClickListener, LocationListener{
	
	private LocationManager lManager;
    private Location location;
    private String select_source = "";
	
	private Button provider;
	private Button getposition;
	private Button save;
	private long id;
	private EditText textLongitude;
	private EditText textLatitude;
	private boolean bUpdateMode;
	private EditText textStreet;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        
        setContentView(R.layout.settings);
        
        lManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
 
        rebootScreen();
        
        provider = (Button) findViewById(R.id.select_provide);
        provider.setOnClickListener(this);
        getposition = (Button) findViewById(R.id.get_position);
        getposition.setOnClickListener(this);
        save = (Button) findViewById(R.id.save_position);
        save.setOnClickListener(this);
        
    	textLongitude = (EditText) findViewById(R.id.latitude);
		textLatitude = (EditText) findViewById(R.id.longitude);
		textStreet = (EditText) findViewById(R.id.namePosition);
		
		Intent i = this.getIntent();
		id = i.getLongExtra(DBAdapter.COL_ID, 0);
		
		if(id==0)
   	 {
   		 bUpdateMode = false;
   	 }
   	 else
   	 {
   		 bUpdateMode = true;
   		 
   		 String url = i.getStringExtra(DBAdapter.COL_LATITUDE);
   		 String title = i.getStringExtra(DBAdapter.COL_LONGITUDE);
   		 String street = i.getStringExtra(DBAdapter.COL_STREET);
   		 textStreet.setText(street);
   		 textLatitude.setText(url);
   		 textLongitude.setText(title);
   		 
   	 }		
        
	}

	@Override
	public void onClick(View v){
		
		switch(v.getId()){
		
		case R.id.select_provide:
				
			selectProvider();
			
			break;
		
		case R.id.save_position:
			
			Intent i = new Intent();
		   	i.putExtra(DBAdapter.COL_LATITUDE, textLatitude.getText().toString());
		   	i.putExtra(DBAdapter.COL_LONGITUDE, textLongitude.getText().toString());
		   	i.putExtra(DBAdapter.COL_STREET, textStreet.getText().toString());
		   	
		   	if(bUpdateMode)
		   			i.putExtra(DBAdapter.COL_ID, id);
		   	setResult(RESULT_OK, i);
		   	finish();
			
			break;
		
		case R.id.get_position:
			
			getPosition();
			
			
			break;
		
		}	
	}
	

	private void rebootScreen(){
		((TextView)findViewById(R.id.latitude)).setText("0.0");
		((TextView)findViewById(R.id.longitude)).setText("0.0");
		((TextView)findViewById(R.id.adress)).setText("");
 
		findViewById(R.id.get_position).setEnabled(false);
		findViewById(R.id.save_position).setEnabled(false);
	}
 
	private void selectProvider() {
		rebootScreen();
 
		List <String> providers = lManager.getProviders(true);
		final String[] sources = new String[providers.size()];
		int i =0;
		
		for(String provider : providers)
			sources[i++] = provider;
 
		new AlertDialog.Builder(GetGPSLocation.this)
		.setItems(sources, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				findViewById(R.id.get_position).setEnabled(true);
				
				select_source = sources[which];
				setTitle(String.format("%s - %s", getString(R.string.app_name),
						select_source));
			}
		})
		.create().show();
	}
	
	private void getPosition() {
		
		setProgressBarIndeterminateVisibility(true);
 
		
		lManager.requestLocationUpdates(select_source, 60000, 0, this);
		
	}
	
	private void putLocation() {
		
		((TextView)findViewById(R.id.latitude)).setText(String.valueOf(location.getLatitude()));
		((TextView)findViewById(R.id.longitude)).setText(String.valueOf(location.getLongitude()));
	}
 
	private void putAdress() {
		//setProgressBarIndeterminateVisibility(true);
 
		Geocoder geo = new Geocoder(GetGPSLocation.this);
		try {
			
			List
			<Address> adresses = geo.getFromLocation(location.getLatitude(),
					location.getLongitude(),1);
 
			if(adresses != null && adresses.size() == 1){
				Address adresse = adresses.get(0);
				
				((TextView)findViewById(R.id.adress)).setText(String.format("%s, %s %s",
						adresse.getAddressLine(0),
						adresse.getPostalCode(),
						adresse.getLocality()));
			}
			else {
				
				((TextView)findViewById(R.id.adress)).setText("The adress could not be determined");
			}
		} catch (IOException e) {
			e.printStackTrace();
			((TextView)findViewById(R.id.adress)).setText("The adress could not be determined");
		}
		//setProgressBarIndeterminateVisibility(false);
	}
 
	public void onLocationChanged(Location location) {
		
		Log.i("Your position have changed","");
		
		setProgressBarIndeterminateVisibility(false);
		
		findViewById(R.id.save_position).setEnabled(true);
		
		this.location = location;
		
		putLocation();
		putAdress();
		
		
		lManager.removeUpdates(this);
	}
 
	public void onProviderDisabled(String provider) {
		
		Log.i("The source is not activated","");
		
		Toast.makeText(GetGPSLocation.this,
				String.format(" The source \"%s\" is desactivated", provider),
				Toast.LENGTH_SHORT).show();
		
		lManager.removeUpdates(this);
		
		setProgressBarIndeterminateVisibility(false);
	}
 
	public void onProviderEnabled(String provider) {
		Log.i("Tuto geolocalisation", "The source is not activated.");
		
	}
	public void onStatusChanged(String provider, int status, Bundle extras) {
		Log.i("The status of the source has changed.","");
	}
}
